package evi.com.evi.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import evi.com.evi.R;
import evi.com.evi.application.MyApplication;
import evi.com.evi.utils.AppUtils;
import evi.com.evi.utils.ConnectUtil;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.MessageDialog;
import evi.com.evi.utils.PopStringList;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.ScreenUtils;
import evi.com.evi.utils.ToastUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 添加商品 两个页面
 *
 * @author MY
 */
public class GoodsAddActivity extends Activity implements View.OnClickListener {

    private ImageView tv_return_back; // 返回
    private TextView tv_save;

    private RelativeLayout rl_goods_sort;
    private TextView tv_goods_sort;
    private ImageView iv_add_image;

    private EditText et_goods_name;
    private EditText et_goods_detail;
    private EditText et_goods_price;

    private TextView tv_title;        //标题
    private String ActType = "";        //添加商品，  编辑商品

    private OkHttpClient client;
    private JSONUtils jsonUtils;

    private String[] id;            //分类的id
    private String[] content;       //分类的名称
    private String cate_id;        //选择的分类ID

    private String INTENT_TYPE = "image/*";
    private int REQUESTCODE = 100;
    private File file;

    private static final File PHOTO_DIR = new File(
            Environment.getExternalStorageDirectory() + "/EVIPhoto");
    private String picName = "";
    private String imgName = "";
    private String userSelectPath = "";
    private static final int CAMERA_WITH_DATA = 3023;
    Bitmap bm = null;
    Handler handler = new Handler();

    private String token;

    private Dialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtils.setTranStatus(this, false, Color.parseColor("#FF6600"));
        MyApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_goods_add);

        ActType = getIntent().getStringExtra("ActType");

        initView();

        client = new OkHttpClient();
        jsonUtils = new JSONUtils();

        getGoodsInfo();
    }


    private void initView() {
        tv_return_back = (ImageView) findViewById(R.id.tv_return_back);
        tv_return_back.setOnClickListener(this);

        tv_save = (TextView) findViewById(R.id.tv_save);
        tv_save.setOnClickListener(this);

        iv_add_image = (ImageView) findViewById(R.id.iv_add_image);
        iv_add_image.setOnClickListener(this);

        et_goods_name = (EditText) findViewById(R.id.et_goods_name);
        et_goods_detail = (EditText) findViewById(R.id.et_goods_detail);
        et_goods_price = (EditText) findViewById(R.id.et_goods_price);
        et_goods_price.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        rl_goods_sort = (RelativeLayout) findViewById(R.id.rl_goods_sort);
        rl_goods_sort.setOnClickListener(this);
        tv_goods_sort = (TextView) findViewById(R.id.tv_goods_sort);

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(ActType);
        if ("添加商品".equals(ActType)) {

        } else if ("编辑商品".equals(ActType)) {

        }
        token = SPUtil.getString(this, "token");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_return_back: // 返回
                this.finish();
                break;
            case R.id.tv_save: // 保存
                save();
                break;
            case R.id.iv_add_image: // 选择图片
                isCamera();
//                getImageview();
//                ToastUtils.showMsg(GoodsAddActivity.this, "选择图片");
                break;
            case R.id.rl_goods_sort: // 选择分类
                new PopStringList().getStringlist(GoodsAddActivity.this, "选择分类", content, id, new PopStringList.Stringcallback() {
                    @Override
                    public void sure(String chosed, String id) {
                        tv_goods_sort.setText(chosed);
                        cate_id = id;
                    }
                });
                break;
            default:
                break;
        }
    }

    //相机或者系统图片
    private void isCamera() {

        AppUtils.showMsgDialog(this, "请选择您的操作", "拍  照", "系统图库", 1, null, new AppUtils.MsgCallBack() {
            @Override
            public void confirmMsg(MessageDialog d) {
                getCamera();

                d.dismiss();
            }

            @Override
            public void cancelMsg(MessageDialog d) {
                getImageview();

                d.dismiss();
            }
        });
    }

    /**
     * 获取图片
     */
    private void getImageview() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(INTENT_TYPE);
        startActivityForResult(intent, REQUESTCODE);
    }

    /**
     * 调用系统照相机并把照片显示到指定位置
     */
    private void getCamera() {
//        toast("测试中");

        try {
            PHOTO_DIR.mkdirs();
            Intent imageCaptureIntent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            picName = getPhotoFileName();
            picName = picName.replace("-", "");
            picName = picName.replace(":", "");
//            picNameList.add(picName);
            File out = new File(PHOTO_DIR, picName);
//            picFileList.add(out);
            Uri uri = Uri.fromFile(out);
            imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(imageCaptureIntent, CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
//            Toast.makeText(this, "doTakePhoto??e=" + e, Toast.LENGTH_LONG)
//                    .show();
            Log.e("TAG", "doTakePhoto??e=" + e);
        }
    }

    //图片名字
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        return dateFormat.format(date) + ".jpg";
    }

    /**
     * 回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        getImageInfo(requestCode, resultCode, data);
    }


    /**
     * 获取图片和图片路径
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void getImageInfo(int requestCode, int resultCode, Intent data) {
//        //获取图片
//        if (data == null) {
//            return;
//        }
        Bitmap bitmap = null;
        ContentResolver resolver = getContentResolver();
        if (requestCode == REQUESTCODE) {
            if(data != null){
                Uri uri = data.getData();
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(resolver, uri);//获得图片
                } catch (IOException e) {
                    e.printStackTrace();
                }
                iv_add_image.setImageBitmap(bitmap);


                //获取图片路径
//            Uri uri = data.getData();
                uri = geturi(data);//解决方案
                String[] pro = {MediaStore.Images.Media.DATA};
                //好像是android多媒体数据库的封装接口，具体的看Android文档
                Cursor cursor = managedQuery(uri, pro, null, null, null);
                Cursor cursor1 = getContentResolver().query(uri, pro, null, null, null);
                //拿到引索
                int index = cursor1.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                //移动到光标开头
                cursor.moveToFirst();
                //最后根据索引值获取图片路径
                String path = cursor.getString(index);

                file = new File(path);
            }
        } else if (requestCode == CAMERA_WITH_DATA) {
            try {
                userSelectPath = PHOTO_DIR + "/" + picName;
                imgName = picName;
//                    int degree = readPictureDegree(userSelectPath);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                bm = BitmapFactory.decodeFile(userSelectPath, options);
                options.inJustDecodeBounds = false;
                int be = (int) (options.outHeight / (float) 200);

                if (be <= 0)
                    be = 1;
                options.inSampleSize = be;
                bm = BitmapFactory.decodeFile(userSelectPath, options);
//                    final Bitmap bitmap = rotaingImageView(degree, bm);
                file = new File(userSelectPath);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        iv_add_image.setImageBitmap(bm);
                    }
                });
            } catch (Exception e) {
                System.out.println("CAMERA_WITH_DATA:e=" + e.getMessage());
            }
        }

    }


    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }

    /**
     * 保存
     */
    private void save() {
//        File image = new File("------文件路径----");
        String name = et_goods_name.getText().toString();
        String detail = et_goods_detail.getText().toString();
        String price = et_goods_price.getText().toString();
        if (file == null) {
            ToastUtils.showMsg(GoodsAddActivity.this, "请选择商品图片");
            return;
        }
        if (TextUtils.isEmpty(cate_id)) {
            ToastUtils.showMsg(GoodsAddActivity.this, "请选择分类");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showMsg(GoodsAddActivity.this, "请输入商品名");
            return;
        }
        if (TextUtils.isEmpty(detail)) {
            ToastUtils.showMsg(GoodsAddActivity.this, "请输入商品详情");
            return;
        }
        if (TextUtils.isEmpty(price)) {
            ToastUtils.showMsg(GoodsAddActivity.this, "请输入商品价格");
            return;
        }

        addGoods();
    }

    private String categoryId;
    private String name;
    private String introduction;
    private String price;

    /**
     * 添加商品
     */
    private void addGoods() {
        dialog = AppUtils.getLoadingDialog(this, "提示", "正在上传，请稍等");
        dialog.show();
        categoryId = cate_id;
        name = et_goods_name.getText().toString();
        introduction = et_goods_detail.getText().toString();

        if (et_goods_name.getText().toString().length() > 8) {
            name = et_goods_name.getText().toString().substring(0, 8);
        }

        if (et_goods_detail.getText().toString().length() > 20) {
            introduction = et_goods_detail.getText().toString().substring(0, 20);
        }

        price = et_goods_price.getText().toString();
        FormBody.Builder builder = new FormBody.Builder();

        RequestBody body = builder
                .add("categoryId", categoryId)
                .add("name", name)
                .add("introduction", introduction)
                .add("price", price)
                .build();


        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.addProduct_url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                dismiss();
                toast("服务器忙碌，请稍后再试");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        final String productId = jsonObject.getJSONObject("data").getString("productId");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                upload(file, productId);
                            }
                        });

                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
                Log.e("分类", "商品信息联网成功" + jsonData);
            }
        });
    }

    //上传图片
    private void upload(File file, String productId) {

        String token = SPUtil.getString(this, "token");
        MediaType MEDIA_TYPE = file.getAbsolutePath().endsWith("png") ?
                MediaType.parse("image/png") : MediaType.parse("image/jpeg");

        RequestBody fileBody = RequestBody.create(MEDIA_TYPE, file);

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("productId", productId)
                .addFormDataPart("imageFile", "image", fileBody)
                .build();
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.productUpdateImage_url)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(GoodsAddActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showMsg(GoodsAddActivity.this, "上传成功");
                                setResult(RESULT_OK);
                                dialog.dismiss();
                                finish();
                            }
                        });
                    } else {
                        dismiss();
                    }
                }
                Log.e("TAG", "上传图片联网成功" + jsonData);
            }
        });
    }

    private void getGoodsInfo() {
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.merchantCategoryProducts_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器忙碌，请稍后再试");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("categories");
                        id = new String[jsonArray.size()];
                        content = new String[jsonArray.size()];
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject sort = jsonArray.getJSONObject(i);
                            id[i] = sort.getString("productCategoryId");
                            content[i] = sort.getString("name");
                        }
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                Log.e("分类", "商品信息联网成功" + jsonData);
            }
        });
    }

    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(GoodsAddActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().deleteActivity(this);
    }
}
